package com.lhn.netty.nio.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * 服务端
 *
 * @author lhn
 * @date 2025/05/28 16:41
 * @since 1.0.0
 **/
public class GroupChatServer {

    private static final int PORT = 6667;

    private Selector selector;

    private ServerSocketChannel listenChannel;

    // 初始化工作
    public GroupChatServer() {
        try {
            // 得到一个选择器
            selector = Selector.open();
            // 创建 ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            // bind  port
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            // 设置为非阻塞
            listenChannel.configureBlocking(false);
            // 将 ServerSocketChannel 注册到选择器上, 关心事件为 OP_ACCEPT
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 监听
    public void listen() {
        System.out.println("监听线程: " + Thread.currentThread().getName());
        try {
            // 循环处理
            while (true) {
            int count = selector.select(2000);
                // 监听到有事件发生
                if (count > 0) {
                    // 遍历得到  selectionKeys
                    Iterator <SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()) {
                        // 取出 selectionKey
                        SelectionKey selectionKey = keyIterator.next();
                        // 判断 事件类型
                        if (selectionKey.isAcceptable()) { // 发生 OP_ACCEPT
                            SocketChannel socketChannel = listenChannel.accept();
                            // 设置非阻塞
                            socketChannel.configureBlocking(false);
                            // 将  socketChannel 注册到 selector
                            socketChannel.register(selector, SelectionKey.OP_READ);
                            System.out.println(socketChannel.getRemoteAddress() + " 上线了");
                        }
                        if (selectionKey.isReadable()) { // 发生 op_read
                            // 获取到事件发生通道
                            //SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                            //socketChannel.configureBlocking(false);
                            //// 读取数据
                            //byte[] bytes = new byte[1024];
                            //int read = socketChannel.read(ByteBuffer.wrap(bytes));
                            //String msg = new String(bytes, 0, read);
                            //System.out.println("from 客户端: " + msg);
                            readData(selectionKey);
                        }
                        keyIterator.remove();
                    }
                } else {
                    System.out.println("没有事件发生");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
    }

    // 读取客户端的消息
    private void readData(SelectionKey key) {
        // 定义一个SocketChannel
        SocketChannel socketChannel = null;
        try {
            socketChannel = (SocketChannel) key.channel();
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int read = socketChannel.read(byteBuffer);
            // 根据 count  判断是否读取到数据
            if (read > 0) {
                //  把缓冲区数据转成字符串
                String msg = new String(byteBuffer.array());
                // 输出到控制台
                System.out.println("from 客户端: " + msg);
                // 向其他 客户端转发消息
                sendInfoToOtherClients(msg, socketChannel);
            }
        } catch (IOException e) {
            try {
                System.out.println(socketChannel.getRemoteAddress() + " 离线了");
                // 取消  注册
                key.cancel();
                // 关闭通道
                socketChannel.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    // 转发消息
    private void sendInfoToOtherClients(String msg, SocketChannel socketChannel) throws IOException {
        System.out.println("服务器转发消息中...");
        System.out.println("转发消息线程: " + Thread.currentThread().getName());
        // 遍历 所有注册到 selector 上的 SocketChannel, 并排除自己
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();
            if (targetChannel instanceof SocketChannel && targetChannel != socketChannel) {
                // 转型
                SocketChannel channel = (SocketChannel) targetChannel;
                // 将 msg 写到通道
                ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes());
                channel.write(byteBuffer);
            }
        }
    }

    public static void main(String[] args) {
        // 创建服务器对象
        GroupChatServer groupChatServer = new GroupChatServer();
        groupChatServer.listen();
    }

}